<?php

namespace app\organization\controller;

use app\common\controller\Frontend;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

/**
 * 登录
 */
class Login extends Frontend
{
    protected array $noNeedLogin = ['pwdLogin', 'checkLogin'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /**
     * 密码登录
     * @return void
     */
    public function pwdLogin(): void
    {
        $param = $this->request->param([
            'username' => '',
            'password' => ''
        ]);
        try {
            $validate = Validate::rule([
                'username' => ValidateRule::isRequire(null, '请输入账号'),
                'password' => ValidateRule::isRequire(null, '请输入密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        //登录
        $res = $this->auth->loginPwd($param['username'], $param['password']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok('登录成功', $res);
    }


    /**
     * 登录验证
     * @return void
     */
    public function checkLogin(): void
    {
        $is_login = $this->auth->isLogin();
        $this->ok(__('Operation completed'), $is_login);
    }

    /**
     * 重置密码
     * @return void
     */
    public function reUpdatePwd()
    {
        $param = $this->request->param([
            'rePwd' => '',
            'password' => ''
        ]);
        try {
            $validate = Validate::rule([
                'rePwd' => ValidateRule::isRequire(null, '请输入原密码'),
                'password' => ValidateRule::isRequire(null, '请输入新密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $res = $this->auth->reUpdatePwd($param['rePwd'], $param['password']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok(__('Password has been modified successfully. Please log in again'));
    }

    /**
     * 登出
     * @return void
     */
    public function logout(): void
    {
        $this->auth->logout();
        $this->ok(__('Token expiration'));
    }
}